package com.baide.sanguanheyi.plc;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: create by DFX
 * @Date: 2020/4/23 22:23
 * @Version: V1.0.0
 * @Tips:
 */
public class NioChannelMap {

    private static ConcurrentHashMap<String, Channel> sessionChannelMap = new ConcurrentHashMap<String, Channel>();
    private static Logger logger = LoggerFactory.getLogger(NioChannelMap.class);

    public static void add(String clientId, Channel channel) {

        if(sessionChannelMap.get(clientId) != null){
            remove(sessionChannelMap.get(clientId));
        }
        sessionChannelMap.put(clientId, channel);
    }

    public static Channel get(String clientId) {
        return sessionChannelMap.get(clientId);
    }

    public static String remove(Channel channel) {
        for (ConcurrentHashMap.Entry<String, Channel> entry : sessionChannelMap.entrySet()) {
            if (entry.getValue() == channel) {
                String clientId = entry.getKey();
                sessionChannelMap.remove(clientId);
                return clientId;
            }
        }
        return "";
    }
}
